package com.nurese.controller;

import com.nurese.entity.Administrator;
import com.nurese.service.AdministratorService;
import com.nurese.utils.MapControll;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    private AdministratorService administratorService;

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Map<String,Object> login(String username, String password, String captcha, HttpSession session){
        System.out.println("/login");

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(captcha)){
            return MapControll.getInstance().error("用户名或密码不正确").getMap();
        }

        String _captcha = (String)session.getAttribute("captcha");
        if(StringUtils.isEmpty(captcha)){
            return MapControll.getInstance().error("验证码不能为空").getMap();
        }
        if(!captcha.equals(_captcha)){
            return MapControll.getInstance().error("验证码错误").getMap();
        }

//        管理员验证登录
        Administrator administrator =administratorService.login(username, password);

        if (administrator != null){
            session.setAttribute("administrator",administrator);
//            session.setAttribute("type",1);
            return MapControll.getInstance().success().add("data",administrator).getMap();
        }else{
            return MapControll.getInstance().error("用户名或密码错误").getMap();
        }

//        return MapControll.getInstance().error().getMap();
    }

}
